<?php
/**
 * PHPExcel 服务层
 * @author maniac
 */
namespace app\common\service;

class PHPExcel extends Base
{
    /**
     * 导出数据
     * @param  array $data 请求的数据
     */
    public function export($title, $data, $filename = '01simple')
    {
        $objPHPExcel = new \PHPExcel();
        foreach ($title as $k => $v) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($k.'1', $v);
            $objPHPExcel->getActiveSheet()->getColumnDimension($k)->setWidth(30);
        }
        $i = 2;
        foreach ($data as $key => $val) {
            foreach ($val as $k => $v) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($k.$i, $v, \PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $i++;
        }
        
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
        $objPHPExcel->setActiveSheetIndex(0);
        
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}
